package com.shimao.celnet.payment.controller;

import com.shimao.celnet.payment.form.IInterfaceLogForm;
import com.shimao.celnet.payment.model.IInterfaceLog;
import com.shimao.celnet.payment.service.IInterfaceLogService;
import com.shimao.celnet.payment.util.FinalUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 接口日志
 * Created by ensure on 2017/12/06.
 *
 */
@Controller
@RequestMapping("/interfaceLogs")
public class IInterfaceLogController {
    protected  Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private IInterfaceLogService localService;

    /**
     * 分页列表查询
     * @param formBean
     * @param pageActionNm
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String getAll(@ModelAttribute IInterfaceLogForm formBean, String pageActionNm, Model model){
        logger.info("查询列表页面--开始");

        if(StringUtils.isNotEmpty(formBean.getGuid())){
            //更新，新增后，重新刷新情况，查询条件清空
            formBean=new IInterfaceLogForm();
        }

        //当前页码设定
        int pageNum=FinalUtil.PAGE_Fist_NUM;

        if(formBean.isIsLastPage()){
            pageNum=formBean.getPages();
        }

        if(!StringUtils.isEmpty(pageActionNm) && !"0".equals(pageActionNm)){
            pageNum=Integer.valueOf(pageActionNm);
        }

        //页面数据查询结果
        formBean = localService.getByPage(formBean, pageNum, FinalUtil.PAGE_LENGHT);

        model.addAttribute("formBean", formBean);

        logger.info("查询列表页面--结束");

        return "interfaceLog/interfaceLogList";
    }


    /**
     * 更新初始化
     * @param
     * @return
     */
    @RequestMapping("/editInfo")
    public String  editInfo(@RequestParam String guid, Model model) {
        logger.info("修改页面--初始化");
        IInterfaceLog editBean = new IInterfaceLog();
        if(StringUtils.isNotEmpty(guid)) {
            //编辑数据取得
            editBean = localService.getByKey(guid);

        }
        IInterfaceLogForm formBean = new IInterfaceLogForm();

        formBean.setGuid(editBean.getGuid());//guid
        formBean.setInterfaceId(editBean.getInterfaceId());//接口编号
        formBean.setInterfaceApi(editBean.getInterfaceApi());//接口api
        formBean.setInterfaceName(editBean.getInterfaceName());//接口中文名称
        formBean.setInterfaceType(editBean.getInterfaceType());//调用类型callIn，callOut
        formBean.setRequestUrl(editBean.getRequestUrl());//访问URL
        formBean.setAppKey(editBean.getAppKey());//应用系统编号
        formBean.setAppName(editBean.getAppName());//应用系统名称
        formBean.setAppToken(editBean.getAppToken());//应用token
        formBean.setStartDate(editBean.getStartDate());//开始时间
        formBean.setEndDate(editBean.getEndDate());//结束时间
        formBean.setConsumeTime(editBean.getConsumeTime());//耗时
        formBean.setRecallNumber(editBean.getRecallNumber());//重发次数
        formBean.setRecallDate(editBean.getRecallDate());//重发时间
        formBean.setErrorcode(editBean.getErrorcode());//应答错误编码
        formBean.setErrormsg(editBean.getErrormsg());//答错误信息
        formBean.setStatus(editBean.getStatus());//接口状态
        formBean.setIsProcess(editBean.getIsProcess());//是否人工处理
        formBean.setProcessInstruction(editBean.getProcessInstruction());//人工处理说明
        formBean.setRequestText(editBean.getRequestText());//请求文本
        formBean.setResponseText(editBean.getResponseText());//应答文本
        formBean.setExceptionInfo(editBean.getExceptionInfo());//异常信息

        model.addAttribute("formBean",formBean);

        return "interfaceLog/interfaceLogInfo";
    }


    /**
     * 更新保存
     * @param
     * @return
     */
    @RequestMapping("/editSave")
    public  @ResponseBody Map<String, Object> editSave(@RequestBody @Valid IInterfaceLog editForm, BindingResult result) {
        logger.info("修改提交--开始");
        //返回map
        Map<String, Object> returnMap = new HashMap<String, Object>();

        //界面输入验证
        if (result.hasErrors()) {
            for(FieldError error:result.getFieldErrors()) {
                returnMap.put(error.getField() + FinalUtil.VALID_MSG, error.getDefaultMessage());
                //验证错误==2
                returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_2);
            }
            logger.debug("修改提交--页面验证出错");
            return returnMap;
        }

        String loginUserGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        editForm.setUpdateUserGuid(loginUserGuid);

        try{
            logger.debug("修改提交--数据保存");
            editForm.setCreatedUserGuid(loginUserGuid);

            localService.update(editForm);

            //成功消息==0
            returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_SCU_0);
            logger.debug(FinalUtil.PAGE_UPD_SCU);
        } catch (Exception e) {
            //失败消息
            returnMap.put(FinalUtil.ERROR_CODE,  FinalUtil.SAVE_ERR_1);
            returnMap.put(FinalUtil.ERROR_MSG,  FinalUtil.PAGE_UPD_ERR);
            e.printStackTrace();
            logger.error(FinalUtil.PAGE_UPD_ERR);
            logger.error(e);
        }
        logger.info("修改提交--结束");
        return returnMap;
    }


}
